/*
 * @Author: z9527
 * @Date: 2022-02-23 16:25:37
 * @LastEditTime: 2022-03-21 16:44:29
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \mallAdmin\src\app\main\config\config-mapping-list\config-mapping-list.component.ts
 */
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ConfigMappingListService } from './config-mapping-list.service';

@Component({
  selector: 'app-config-mapping-list',
  templateUrl: './config-mapping-list.component.html',
  styleUrls: ['./config-mapping-list.component.scss']
})
export class ConfigMappingListComponent implements OnInit {
  imgLists: any = ['https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', 'https://img.alicdn.com/tfs/TB1g.mWZAL0gK0jSZFtXXXQCXXa-200-200.svg'];

  searchParams: any = {
    name: ''
  };

  tableParams = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  tableData: any = [];

  // 新建 Modal
  isVisible: boolean = false;
  submitLoading: boolean = false;
  modalType: number = 0; // 0: 新增 1: 编辑
  modalItem: any = {};
  validateForm: any = {
    name: '',
    key: '',
    content: '',
    remarks: ''
  };

  mappingChannelOptions = [
    {value: '2', label: 'PC端', content: ''},
    {value: '17', label: '移动端', content: ''},
    {value: '15', label: '小程序', content: ''},
    {value: '5', label: '爱乐物', content: ''},
    {value: '19', label: '回收支付宝小程序', content: ''},
    {value: '23', label: 'WEB端', content: ''}
  ];

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private services: ConfigMappingListService
  ) { }

  ngOnInit(): void {
    this.loadTable()
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.tableLoading = true;
    const res: any = await this.services.queryMappingList(params);
    this.tableParams.tableLoading = false;
    
    if (res.code === 0) {
      const { records, total } = res.data || {};
      this.tableData = records || [];
      this.tableParams.total = total || 0;
    } else {
      this.message.error(res.message);
    }
  }

  searchData() {
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData() {
    for (let key in this.searchParams) {
      this.searchParams[key] = '';
    };
    this.tableParams.page = 1;
    this.loadTable();
  }

  showModal(type: number, item?: any) {
    this.modalType = type;
    this.modalItem = {};
    for (let key in this.validateForm) {
      this.validateForm[key] = '';
    }
    this.mappingChannelOptions.map((item: any) => item.content = '');
    
    // Edit Item
    if (type === 1) {
      this.modalItem = item;
      for(let key in this.validateForm) {
        this.validateForm[key] = item[key] || '';
      }
      let tmpObj: any = item.content ? JSON.parse(item.content) : null;
      this.mappingChannelOptions.forEach((item: any) => {
        item.content = tmpObj ? tmpObj[item.value] : '';
      })
    }
    this.isVisible = true;
  }

  async updateSubmit() {
    if (!this.verifData()) {
      return
    }
    this.validateForm.content = JSON.stringify(this.conversionObj(this.mappingChannelOptions));
    let params = {
      ...this.validateForm
    }

    this.submitLoading = true;
    let res: any;
    switch (this.modalType) {
      case 0:
        res = await this.services.saveMappingItem(params);
        break;
      case 1:
        params.id = this.modalItem.id;
        res = await this.services.updateMappingItem(params);
        break;
    }
    this.submitLoading = false;
    
    if (res.code === 0) {
      this.isVisible = false;
      this.message.success('操作成功');
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  verifData() {
    if (this.validateForm.name === '') {
      this.message.warning('请输入名称');
      return false;
    } else if (this.validateForm.key === '') {
      this.message.warning('请输入标识');
      return false;
    } else {
      return true;
    }
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 数组对象转化
  conversionObj(arr: Array<any>) {
    return arr.reduce((obj: any, item: any) => ({
      ...obj, [item.value]: item.content
    }), {})
  }

  mappingFilter(num: any, item: any) {
    let tmpObj: any = item.content ? JSON.parse(item.content) : {};
    return tmpObj[num] || '-';
  }
}
